package com.yonyou.distribute.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * p21  redis 乐观锁解决超卖
 *
 * http://localhost/redis/multi/stock/deduct
 * http://localhost:80/redis/multi/stock/deduct
 *
 * 缺点：
 * 1、性能低
 */
@Slf4j
@Service
public class RedisService_2 {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 按说这里是解决超卖的  但是稳定卖了双倍
     */
    @Transactional
    public void deduct() {
        this.stringRedisTemplate.execute(new SessionCallback<Object>() {

            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                // watch multi exec
                operations.watch("stock");
                // 1、查询库存
                String stock = operations.opsForValue().get("stock").toString();
                // 2、判断库存是否充足
                if(!StringUtils.isEmpty(stock)){
                    Integer st = Integer.valueOf(stock);
                    if(st > 0){
                        operations.multi();
                        //3、更新库存到数据库
                        operations.opsForValue().set("stock", String.valueOf(--st));
                        //4、如果执行事务的返回结果为空，则代表减库存失败，重试
                        List exec = operations.exec();
                        if(CollectionUtils.isEmpty(exec)){
                            try {
                                Thread.sleep(40);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            deduct();
                        }else{
                            return exec;
                        }
                    }
                }
                return null;
            }
        });
    }

    /**
     * 直接这么写报错
     * io.lettuce.core.RedisCommandExecutionException: ERR EXEC without MULTI
     */
    @Transactional
    public void deduct1() {
        // watch multi exec
        this.stringRedisTemplate.watch("stock");
        // 1、查询库存
        String stock = this.stringRedisTemplate.opsForValue().get("stock");
        // 2、判断库存是否充足
        if(!StringUtils.isEmpty(stock)){
            Integer st = Integer.valueOf(stock);
            if(st > 0){
                this.stringRedisTemplate.multi();
                //3、更新库存到数据库
                this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
                this.stringRedisTemplate.exec();
            }
        }
    }

}
